from flask import Flask, request,json
import optimize,shape,B_Spline
from matplotlib import pyplot as plt
import time
import path

app = Flask(__name__)
plt.switch_backend('agg')

@app.after_request
def cors(environ):#解决跨域问题
    environ.headers['Access-Control-Allow-Origin']='*'
    environ.headers['Access-Control-Allow-Method']='*'
    environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
    return environ

def save_fig(optim,path_curve):
    px = optim.scene.joint[:,:1].flatten()
    py = optim.scene.joint[:,1:].flatten()
    cx = path_curve[:,:1].flatten()
    cy = path_curve[:,1:].flatten()

    plt.title('Path')
    for sp in optim.scene.barriers:
        sp.draw()
    plt.scatter(px,py,s=5,c='r')
    #plt.plot(ox,oy)
    plt.scatter(cx,cy,s=1,c='g')
    plt.savefig('./pytool/front_res/path_{}.png'.format(time.gmtime().tm_sec), dpi=300)
    plt.clf()

@app.route('/getPath',methods=['POST'])
def getPath():
    print('getPath...')
    data = json.loads(request.form.to_dict()['data'])
    border = data['border']
    dense = data['dense']
    barriers = data['barrier']

    pillar_list = []
    for barrier in barriers:
        pillar_list.append(shape.Pillar(barrier['pos'],barrier['tilt'],barrier['len']))

    # optim = optimize.Path_Optimize(border, dense, pillar_list)
    # path_list = optim.run()

    # bs = B_Spline.BSpline(path_list)
    # path_curve = bs.curve(500)

    pth = path.Path(border,dense,pillar_list)
    path_o = pth.Path_Global_Search(500)
    pth.Path_Through_Ring(path_o[-1],path_o[0])
    path_curve = pth.get_path()

    #save_fig(optim, path_curve)

    dictData = {'path':path_curve, 'type':'s'}
    print('ok')

    jsonData=json.dumps(dictData)
    return jsonData

if __name__ == '__main__':
   app.run(debug = True)